<%@page  import="merlin.beans.*,merlin.dao.*,merlin.managers.*,merlin.servlets.*,merlin.utils.*" %>

<%!
	// User types
	static final Integer USER_TYPE_MERLIN_RESEARCHER = new Integer(1);
	static final Integer USER_TYPE_FREE_UPDATES = new Integer(2);
%>


<%
	// sanity check
	if(session.getAttribute("username") == null){
		response.sendRedirect("login.jsp");
		return;
	}

	Integer iObj = (Integer)session.getAttribute("userType");
%>

<html>
	<head>
	<meta HTTP-EQUIV="Cache-Control"  CONTENT="no-cache" />
	<meta HTTP-EQUIV="Expires"        CONTENT="1 Jan 1980" />
	<meta HTTP-EQUIV="MaxAge"         CONTENT="0" />
	<meta HTTP-EQUIV="Pragma-Control" CONTENT="no-cache" />
		<script>

			////////////// Utility Functions ////////////////////

			function disableEnable(bFlag){
				document.frmSearch.txtSearch.disabled = bFlag;
				document.frmSearch.btnSearch.disabled = bFlag;
				document.frmSearch.lstCompanies.disabled = bFlag;
				document.frmSearch.btnAddCompany.disabled = bFlag;
				document.frmSearch.btnRemoveCompany.disabled = bFlag;
				document.frmSearch.btnUpdate.disabled = bFlag;
				document.frmSearch.lstSelectedCompanies.disabled = bFlag;
				document.frmSearch.lstDirectors.disabled = bFlag;
				document.frmSearch.btnPrintPDF.disabled = bFlag;
			}

			function isBlank(str){
				var len = str.length;
				if(len==0)return true;	// zero-length string
				for(i=0;i<len;i++){
					if(str.charAt(i) !=' ' && str.charAt(i) !='\n')return false; //some character is there
				}
				return true;
			}

			function getSelectedCompanies(frm){

				var lstLen = frm.lstSelectedCompanies.length;
				if(lstLen == 0 )return "";

				var reportTitles ="";
				for(i=0;i < lstLen - 1;i++){
					reportTitles += frm.lstSelectedCompanies.options[i].value + "|" + frm.lstSelectedCompanies.options[i].text + "|";
				}
				reportTitles += frm.lstSelectedCompanies.options[lstLen-1].value + "|" + frm.lstSelectedCompanies.options[lstLen-1].text

				return reportTitles;
			}
			////////////// Ends Utility Functions //////////////////

			/////////////////Message Display Functions ///////////
			function displayMessage(message){
				message = "<SPAN style='color:GREEN; font: 12px arial, verdana, sans-serif ;font-weight:bold;'>" + message + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = message;
			}

			function displayError(errMessage){
				errMessage = "<SPAN style='color:red; font: 12px arial, verdana, sans-serif ;font-weight:bold;'>" + errMessage + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = errMessage;
			}

			function clearMessage(){
				var emptyMessage = "<SPAN style='font: 12px arial, verdana, sans-serif ;font-weight:bold;'>&nbsp;</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = emptyMessage;
			}

			//////////////Ends Message Display Functions /////////

			//////////////Search Functions //////////////////////
			function searchCompanyByKeyword(strSearch,frm){

				if(isBlank(strSearch)){
					alert("Cannot leave the search field blank");
					return false;
				}
				if(strSearch.length < 3){
					alert("Enter at least 3 characters in the search field");
					return false;
				}

				// disable the various UI components so that the user cannot generate
				// another request as long as the search is going on.
				disableEnable(true);

				//parent.frameMessage.displayMessage("Searching...");
				displayMessage("Searching.....");
   				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByKeyword";
   				parent.frameSearch.document.frmSearch.hidSearch.value=strSearch;
   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm);
   				parent.frameSearch.document.frmSearch.submit();
   				return true;
			}

			function searchCompanyByCompanyNumber(strNumber,frm){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}

				// disable the various UI components so that the user cannot generate
				// another request as long as the search is going on.
				disableEnable(true);

				//parent.frameMessage.displayMessage("Searching...");
				displayMessage("Searching.....");
   				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByCompanyNumber";
   				parent.frameSearch.document.frmSearch.hidSearch.value=strNumber;
   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm);
   				parent.frameSearch.document.frmSearch.submit();
			}

			function searchCompanyByDirector(strNumber,frm){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}

				// disable the various UI components so that the user cannot generate
				// another request as long as the search is going on.
				disableEnable(true);

				//parent.frameMessage.displayMessage("Searching...");
				displayMessage("Searching.....");
				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByDirector";
   				parent.frameSearch.document.frmSearch.hidSearch.value=strNumber;
   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm);
   				parent.frameSearch.document.frmSearch.submit();
			}
			//////////////Ends Search Functions /////////////////////////
			/********
			// moves an item from the lstFrom list to lstTo
			function transferCompany(lstFrom,lstTo){
		    	var lstFromlen = lstFrom.length ;
		    	var isAnySelected = false;
    			for ( i=0; i<lstFromlen ; i++){
        			if (lstFrom.options[i].selected == true ) {
        				// check if the company already exists in the selected companies list.
        				var valCompany = lstFrom.options[i].value;
        				var exists = false;
        				var lstTolen = lstTo.length;
        				for(j=0;j<lstTolen;j++){
        					if(valCompany == lstTo.options[j].value){
        						alert("Company already selected");
        						exists = true;
        						lstFrom.options[i].selected = false;
								break;
        					}
        				}
        				if(! exists){
	            			lstTolen = lstTo.length;
    	        			lstTo.options[lstTolen]= new Option(lstFrom.options[i].text,lstFrom.options[i].value);
    	        		}
        				isAnySelected = true;
					}
    			}
				if(!isAnySelected){
					alert("Select a company to add");
					return;
				}
    			for ( i = (lstFromlen -1); i>=0; i--){
        			if (lstFrom.options[i].selected == true ) {
            			lstFrom.options[i] = null;
        			}
    			}
   				// sort the data.
   				sortSelect(lstTo,true);
			}
			**************/

			function transferCompany(lstFrom,lstTo){
				try{
					var index = lstFrom.selectedIndex;
					if(index == -1){
						alert("Select a company to add");
						return;
					}
					// check if the company already exists in the selected companies list.
					var valCompany = lstFrom.options[index].value;
					var exists = false;
					var lstTolen = lstTo.length;
					for(j=0;j<lstTolen;j++){
						if(valCompany == lstTo.options[j].value){
							alert("Company already selected");
        					exists = true;
	        				lstFrom.options[index].selected = false;
							break;
	    		    	}
    	    		}
			        if(! exists){
						// add the company to the list
	    			    var aOption = document.createElement("OPTION");
						aOption.text = lstFrom.options[index].text;
						aOption.value = lstFrom.options[index].value;
						// browser specific addition, different in Mac Safari.
						if(navigator.userAgent.indexOf("Safari") > -1){
							// Mac Safari
							lstTo.add(aOption);
						}else{
							// other browsers.
							lstTo.options.add(aOption);
						}

						// and remove it from the other
						lstFrom.remove(index);

						// sort the data.
						sortSelect(lstTo);
					}
				}catch(e){
					alert("transferCompany : " + e.message);
				}
			}

			function sendReportData(frm){
			<%
				if(USER_TYPE_MERLIN_RESEARCHER.equals(iObj)){
			%>
				if(frm.lstSelectedCompanies.length == 0){
					alert("There must be at least one company selected");
					return;
				}
			<%
				}
			%>
				//parent.frameMessage.displayMessage("Sending Mail...");
				displayMessage("Sending Mail...");
				/*
				var reportTitles ="";
				var lstLen = frm.lstSelectedCompanies.length;
    			for(i=0;i < lstLen - 1;i++){
					reportTitles += frm.lstSelectedCompanies.options[i].value + "|" + frm.lstSelectedCompanies.options[i].text + "|";
				}
    			reportTitles += frm.lstSelectedCompanies.options[lstLen-1].value + "|" + frm.lstSelectedCompanies.options[lstLen-1].text

    			//alert(reportTitles);
    			frm.hidReports.value=reportTitles;
    			*/
    			frm.mode.value="sendMail";
    			frm.hidCompanies.value= getSelectedCompanies(frm);
    			frm.submit();
			}

			function deleteCompany(lst){
				var isAnySelected = false;
				/*
				if(lst.selectedIndex > -1){
     				lst.options[lst.selectedIndex] = null;
				}
				*/
				for(i = lst.length -1;i>=0;i--){
					if(lst.options[i].selected == true){
						lst.options[i] = null;
						isAnySelected = true;
					}
				}
				if(!isAnySelected){
					alert("Select a company to delete");
				}
			}

        	// sort function - ascending (case-insensitive)
	        function sortFuncAsc(record1, record2) {
    	        var value1 = record1.optText.toLowerCase();
        	    var value2 = record2.optText.toLowerCase();
            	if (value1 > value2) return(1);
	            if (value1 < value2) return(-1);
    	        return(0);
        	}

			/***********************
    	    function sortSelect(selectToSort, ascendingOrder) {
        	    if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

            	// copy options into an array
	            var myOptions = [];
    	        for (var loop=0; loop<selectToSort.options.length; loop++) {
        	        myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
            	}

	            // sort array
    	        if (ascendingOrder) {
        	        myOptions.sort(sortFuncAsc);
            	} else {
                	myOptions.sort(sortFuncDesc);
	            }

    	        // copy sorted options from array back to select box
        	    selectToSort.options.length = 0;
            	for (var loop=0; loop<myOptions.length; loop++) {
                	var optObj = document.createElement('option');
	                optObj.text = myOptions[loop].optText;
    	            optObj.value = myOptions[loop].optValue;
        	        selectToSort.options.add(optObj);
            	}
	        }
	        **********************/

		    // sort the select object in ascending order.
			function sortSelect(selectToSort) {
				try{
					// copy options into an array
				    var myOptions = new Array();
					for (var loop=0; loop<selectToSort.options.length; loop++) {
						myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
					}

					// sort array
					myOptions.sort(sortFuncAsc);

					// copy sorted options from array back to select box
					selectToSort.options.length = 0;

					// browser identification
					var isSafari =	(navigator.userAgent.indexOf("Safari") > -1)? true: false;

					for (var loop=0; loop<myOptions.length; loop++) {
						var optObj = document.createElement('option');
						optObj.text = myOptions[loop].optText;
						optObj.value = myOptions[loop].optValue;
						if(isSafari){
							selectToSort.add(optObj);
						}else{
							selectToSort.options.add(optObj);
						}
					}
				}catch(e){
					alert("sortSelect : " + e.message);
				}
			}

			function generatePDF(companyId){
				if(companyId == null || companyId==""){
					alert("Please select a company from the search results list");
				}else{
					// open on a new window
					window.open("merlin?mode=createPDF&companyId=" + companyId,"pdf","height=600,width=600,resizable=yes,menubar=yes,scrollbars=yes,toolbar=no");
   				}
			}
		</script>
	    <link href="../mr_css/master.css" rel="stylesheet" type="text/css">
	</head>
<body>

		<jsp:include page = "mr_header2.jsp"/>

		<DIV ALIGN="CENTER" ID="divMessage">&nbsp;</DIV>

<table cellpadding="0" cellspacing="0">
 <tr>
  <td><div class="wideColumn">
		  <div id="orangeBar">
			<h5>Free Updates</h5>
		  </div>

  <div style="border: 1px solid black; background-color: white; margin: 5px 5px 5px 5px;">
  <!-- Page title and help button -->
  <div style="padding: 3px 5px 8px 5px;">
					<FORM name="frmSearch" method="post" target="_top" action="../merlin" onsubmit="searchCompanyByKeyword(this.txtSearch.value,this);return false;">
  <!-- Page title and help button -->
  <div style="padding: 3px 5px 8px 5px;">
    <p><a href="javascript: popup('help_foursteps.jsp', 'help');"><img src="../images/help.gif" style="width: 60px; border:none; height: 21px; float: right;" alt="help" title="help"></a>
        <br />
        <%if (!StringUtils.isEmpty(selectedCompanyNumber)) {%>
        <a href="javascript: popup('addCompaniesStatic.jsp?companyNumber=<%=selectedCompanyNumber%>', 'help');" style="float: right;"><img src="../images/print.gif" alt="help" style="border:none;" title="Render this page as a PDF"></a>
        <%}%>
      Add further relevant companies if required or simply request a free update below.
    </p>
  </div>
  <!-- *********************** -->
  						<input type="hidden" name="hidCompanies">
						<input type="hidden" name="mode">
						<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; PADDING-TOP: 3px">
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 720px" cellpadding="1" cellspacing="0">
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%">
										<b>Search for NAME, KEYWORD, DIRECTOR, REGISTRATION NUMBER or ADDRESS.</b><br>
									</td>
								</tr>
								<tr>
									<td>
										<input name="txtSearch" style="TEXT-TRANSFORM: uppercase; WIDTH: 480px;FONT: 11px arial, verdana, sans-serif;"  >
										<input name="btnSearch" type="submit" style="FONT-SIZE: 11px; WIDTH: 95px" value="Search For Firm  >" > <!-- onclick="searchCompanyByKeyword(this.form.txtSearch.value,this.form)" -->
										&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button"  name="btnPrintPDF" style="FONT-SIZE: 11px; WIDTH: 95px" value="Print PDF" onclick="generatePDF(this.form.lstCompanies.value)">
									</td>
								</tr>
							</table>
						</div>
						<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 7px; PADDING-TOP: 5px">
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="1" cellspacing="0">
								<tr>
									<td style="WIDTH: 260px">
										<span style="FONT: 11px arial, verdana, sans-serif">The following companies were found by this search<br >(click to view a company of interest)</span>
										<SELECT name="lstCompanies" size="4" MULTIPLE style="WIDTH: 250px; FONT: 11px arial, verdana, sans-serif;" onchange="searchCompanyByCompanyNumber(this.value,this.form)">
										</SELECT>
									</td>
									<td style="TEXT-ALIGN: center">
										<input type="button" name="btnAddCompany" value="Add Company  >"  style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="transferCompany(this.form.lstCompanies,this.form.lstSelectedCompanies)">
										<input type="button" name="btnRemoveCompany" value="   < Remove Company" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="deleteCompany(this.form.lstSelectedCompanies)">
										<%
											String strButtonCaption = null;
											if(USER_TYPE_FREE_UPDATES.equals(iObj)){
												strButtonCaption = "Send FREE Update";
											}else{
												strButtonCaption = "Send List";
											}
										%>
										<input type="button" name="btnUpdate" value="<%= strButtonCaption %>" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="sendReportData(this.form)">
									</td>
									<td style="WIDTH: 260px; TEXT-ALIGN: right">
										<span style="FONT: 11px arial, verdana, sans-serif">Companies to include in your new report<br>(click to delete a company)</span>
										<SELECT name="lstSelectedCompanies" size="4" MULTIPLE style="WIDTH: 250px; FONT: 11px arial, verdana, sans-serif;"> <!-- onchange="searchCompanyByCompanyNumber(this.value,this.form)" -->
										<%
											String strCompanies = (String)session.getAttribute("selectedCompanies");
											if(strCompanies != null && strCompanies.length() > 0){
												String arrCompanies[] = strCompanies.split("\\|");
                                           		for(int i=0;i< arrCompanies.length-1;i+=2){
											  		out.println("<option value=\'" + arrCompanies[i] + "\'>" + arrCompanies[i+1] + "</option>");
											  	}
											}
										%>
										</SELECT>
									</td>
								</tr>
							</table>
						</div>
						<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 8px; PADDING-TOP: 3px" >
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="0" cellspacing="0">
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 250px">
										<strong>Address</strong>
									</td>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%">
										<strong>Shareholders</strong>
									</td>
								</tr>
								<tr>
									<td>
										<DIV id="divAddress" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto; HEIGHT:70px; WIDTH: 240px; FONT: 11px arial, verdana, sans-serif;">
										</DIV>
									</td>
									<td>
										<DIV id="divShareholders" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px; FONT: 11px arial, verdana, sans-serif;" >
										</DIV>
									</td>
								</tr>
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Directors &amp; Company Secretary</strong></td>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Parent, Subsidiary Details</strong></td>
								</tr>
								<tr>
									<td>
										<SELECT name="lstDirectors" style="MARGIN: 0px 10px 0px 0px;HEIGHT:72px; WIDTH: 240px;FONT: 11px arial, verdana, sans-serif;" MULTIPLE onchange="searchCompanyByDirector(this.value,this.form)">
										</SELECT>
									</td>
									<td>
										<DIV id="divSubsidiary" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px;FONT: 11px arial, verdana, sans-serif;" >
										</DIV>
									</td>
								</tr>
								<tr>
									<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Business Description</strong></td>
								</tr>
								<tr>
									<td colspan="2"><DIV style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:60px; FONT: 11px arial, verdana, sans-serif;" id="divBusinessDescription"></DIV>
									</td>
								</tr>
								<tr>
									<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Summary Financials</strong>
									</td>
								</tr>
								<tr>
									<td colspan="2">
										<DIV id="divSummaryFinancial" style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:220px; FONT: 11px arial, verdana, sans-serif;">
										</DIV>
									</td>
								</tr>
							</table>
						</div>
					</FORM>
				</div></div></div>
				</td>
			</tr>
		</table>
		<jsp:include page="mr_footer.jsp"/>
	</body>